package com.sk.seckilldemo.service;

import com.sk.seckilldemo.entity.SeckillActivity;
import com.sk.seckilldemo.entity.SeckillOrder;
import com.sk.seckilldemo.entity.request.SeckillRequest;
import com.sk.seckilldemo.enums.ResultCodeEnum;
import com.sk.seckilldemo.exception.CustomException;
import com.sk.seckilldemo.mapper.OrderMapper;
import com.sk.seckilldemo.mapper.SeckillActivityMapper;
import com.sk.seckilldemo.util.Response;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.Duration;

/**
 * 订单处理服务
 * */
@Service
@Transactional //增加事务处理注解
@RequiredArgsConstructor
public class OrderService {
    private final OrderMapper orderMapper;
    private final SeckillActivityMapper activityMapper;
    //引入订单生成服务
    private final OrderNoGenerator orderNoGenerator;
    private RedisTemplate<String,Object> redisTemplate;

    /**
     * 创建一个秒杀订单
     * 参数SeckillRequest对象，其包含了user_id,activityId
     * */
    public void createSeckillOrder(SeckillRequest seckillRequest){
        // 1. 校验库存（数据库层面二次校验）
        SeckillActivity activity = activityMapper.selectById(seckillRequest.getActivityId());
        if(activity.getStock()<=0){
            throw new CustomException(ResultCodeEnum.STOCK_NOT_ENOUGH);
        }

        // 2. 扣减库存
        int affected = activityMapper.reduceStock(seckillRequest.getActivityId());
        if(affected == 0){
            throw new CustomException(ResultCodeEnum.STOCK_NOT_ENOUGH);
        }

        // 3. 生成订单号
        //调用订单号生成服务中的generateSeckillOrderNo()方法，生成订单编号
        String orderNo = orderNoGenerator.generateSeckillOrderNo();

        // 4. 创建订单
        SeckillOrder order = new SeckillOrder();
        order.setUser_id(seckillRequest.getUser_id());
        order.setActivityId(seckillRequest.getActivityId());
        order.setOrderNo(orderNo);

        orderMapper.insert(order);

        // 5. 设置订单超时（10分钟未支付自动取消）
        redisTemplate.opsForValue().set("order:timeout:"+orderNo,"1", Duration.ofMinutes(10));
    }

    /**
     * 订单支付成功处理
     * */
    @Transactional(rollbackFor = Exception.class)
    public void processPaySuccess(String orderNo){
        // 1.更新订单状态
        SeckillOrder order = new SeckillOrder();
        order.setOrderNo(orderNo);
        order.setOrder_status(1);
        orderMapper.updateStatusByOrderNo(order);

        // 2.从Redis中删除超时标记
        redisTemplate.delete("order:timeout:"+orderNo);

        // 3.其他业务处理（发货、通知等）
        // 这里功能略
    }

    /**
     * 订单超时处理
     * */
    @Transactional(rollbackFor = Exception.class)
    public void processOrderTimeout(String orderNo){
        // 1.查询订单
        SeckillOrder order = orderMapper.selectByOrderNo(orderNo);
        if(order==null||order.getOrder_status()!=0){
            // 订单不存在或状态已变更
            throw new CustomException(ResultCodeEnum.ORDER_ERROR_NONE);
        }

        // 2.更新订单状态为已取消
        order.setOrder_status(2);
        orderMapper.updateStatusByOrderNo(order);

        // 3.恢复库存
        activityMapper.increaseStock(order.getActivityId());

        // 4.消除用户参与标记（允许用户重写参与秒杀活动）
        redisTemplate.delete("seckill:user:"+order.getActivityId()+":"+order.getUser_id());

    }
}
